package com.dycong.common.network;

import net.sf.json.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientByteArrayPost {

    private static final String                       HTTP            = "http";
    private static final String                       HTTPS           = "https";
    private static SSLConnectionSocketFactory sslsf           = null;
    private static PoolingHttpClientConnectionManager cm              = null;
    private static SSLContextBuilder builder         = null;
    private static int                                size            = 1 << 23;
    private static int                                DEFAOUT_TIMEOUT = 300000;
    private static String                             DEFAOUT_CHARSET = "UTF-8";
    private static Log log             = LogFactory.getLog(HttpClientByteArrayPost.class);

    static {
        try {
            builder = new SSLContextBuilder();
            // 全部信任 不做身份鉴定
            builder.loadTrustMaterial(null, new TrustStrategy(){

                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            });
            sslsf = new SSLConnectionSocketFactory(builder.build(),
                new String[] {"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register(HTTP, new PlainConnectionSocketFactory()).register(HTTPS, sslsf).build();
            cm = new PoolingHttpClientConnectionManager(registry);
            cm.setMaxTotal(200);
        } catch (Exception e) {
            log.error("exception:{}",e);
        }
    }

    /**
     * httpClient post请求
     * 
     * @param url 请求url
     * @param header 头部信息
     * @param param 请求参数 form提交适用
     * @param entity 请求实体 json/xml提交适用
     * @return 可能为空 需要处理
     * @throws Exception
     *
     */
    public static String post(String url, Map<String, String> header, Map<String, String> param, HttpEntity entity)
        throws Exception {
        String result = "";
        CloseableHttpClient httpClient = null;
        try {
            httpClient = getHttpClient();
            HttpPost httpPost = new HttpPost(url);
            // 设置头信息
            if (MapUtils.isNotEmpty(header)) {
                header.forEach((key,value) -> {
                    httpPost.addHeader(key,value);
                });
            }
            // 设置请求参数
            if (MapUtils.isNotEmpty(param)) {
                List<NameValuePair> formparams = new ArrayList<NameValuePair>();
                param.forEach((key,value) -> {
                    formparams.add(new BasicNameValuePair(key, value));
                });
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
                httpPost.setEntity(urlEncodedFormEntity);
            }
            // 设置实体 优先级高
            if (entity != null) {
                httpPost.setEntity(entity);
            }
            HttpResponse httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity resEntity = httpResponse.getEntity();
                result = EntityUtils.toString(resEntity);
            } else {
                readHttpResponse(httpResponse);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
        }
        return result;
    }

    private static CloseableHttpClient getHttpClient() throws Exception {
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm)
            .setConnectionManagerShared(true).build();
        return httpClient;
    }

    private static String readHttpResponse(HttpResponse httpResponse) throws ParseException, IOException {
        StringBuilder builder = new StringBuilder();
        // 获取响应消息实体
        HttpEntity entity = httpResponse.getEntity();
        // 响应状态
        builder.append("status:" + httpResponse.getStatusLine());
        builder.append("headers:");
        HeaderIterator iterator = httpResponse.headerIterator();
        while (iterator.hasNext()) {
            builder.append("\t" + iterator.next());
        }
        // 判断响应实体是否为空
        if (entity != null) {
            String responseString = EntityUtils.toString(entity);
            builder.append("response length:" + responseString.length());
            builder.append("response content:" + responseString.replace("\r\n", ""));
        }
        return builder.toString();
    }

    /**
     * 直接提交一段JSON文本数据
     * 
     * @param headers 头部信息
     * @param url 请求URL
     * @param param 参数 json对象
     * @return
     * @throws Exception
     */
    public static String postJson(Map<String, String> headers, String url, JSONObject param) throws Exception {
        String result = "";
        CloseableHttpClient httpClient = null;
        try {
            httpClient = getHttpClient();
            HttpPost httpPost = new HttpPost(url);
            // 设置头信息
            if (MapUtils.isNotEmpty(headers)) {
                headers.forEach((key,value) -> {
                    httpPost.addHeader(key, value);
                });
            }
            httpPost.setEntity(new StringEntity(param.toString(), Charset.forName("UTF-8")));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity resEntity = httpResponse.getEntity();
                result = EntityUtils.toString(resEntity);
            } else {
                result = readHttpResponse(httpResponse);
            }
            log.info("===========================================" + url + "===" + result
                + "=================================");
        } catch (Exception e) {
            throw e;
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
        }
        return result;
    }


    /**
     *@see 字节数据对文本模拟文件提交
     * @param headers
     * @param url
     * @param content
     * @param params
     * @return
     * @throws Exception
     */
    public static String postMultipartUpload(Map<String, String> headers, String url, byte[] content,Map<String,String> params) throws Exception {
        String result = "";
        CloseableHttpClient httpClient = null;
        try {
            httpClient = getHttpClient();
            MultipartEntityBuilder multipartEntityBuilder=  MultipartEntityBuilder.create();
            multipartEntityBuilder .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .addBinaryBody("content", (byte[]) content, ContentType.DEFAULT_BINARY,"content");

            if (MapUtils.isNotEmpty(params)) {
                params.forEach((key,value) -> {
                    multipartEntityBuilder.addTextBody(key,value);
                });
            }
            HttpEntity data =multipartEntityBuilder.build();
            RequestBuilder requestBuilder= RequestBuilder
                    .post(url)
                    .setEntity(data);
            if (MapUtils.isNotEmpty(headers)) {
                headers.forEach((key,value) -> {
                    requestBuilder.setHeader(key,value);
                });
            }
            HttpUriRequest request = requestBuilder.build();
            HttpResponse httpResponse = httpClient.execute(request);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            JSONObject resultJson=new JSONObject();
            if (statusCode == HttpStatus.SC_OK) {
                resultJson.put("code",statusCode);
               return resultJson.toString();
            } else {
                result = readHttpResponse(httpResponse);
                resultJson.put("code",statusCode);
                result=resultJson.toString();
            }
            log.info("===========================================" + url + "===" + result
                    + "=================================");
        } catch (Exception e) {
            throw e;
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
        }
        return result;
    }

}
